package com.hitqz.robot.biz.flow.component.agv;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.TicketsTask;
import com.hitqz.robot.biz.flow.util.LiteFlowUtil;
import com.hitqz.robot.biz.service.RobotService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author xupkun
 * @date 2025/5/8
 */

@Slf4j
@LiteflowComponent(value = "RefuellingFinish", name = "[轮对/轮轴]换料完成查询状态重复发")
@AllArgsConstructor
public class RefuellingFinish extends NodeComponent {

    private final RobotService robotService;

    private final RestTemplate restTemplate;

    private static final Table<String, String, String> COMMANDS = HashBasedTable.create();

    static {
        COMMANDS.put("5241,5242", "5241", "8");
        COMMANDS.put("5243,5244", "5243", "8");
    }

    @Override
    public void process() throws Exception {

        LiteFlowUtil.checkInterruptFlag();
        FlowContextDto dto =  this.getRequestData();
        TicketsTask task = dto.getTicketsTask();
        log.info("潜伏车的任务数据 {}", task.getParseOrderParams());
        Robot robot = robotService.getDefaultRobot();
        FlowPatrolPreAndEndTicketsDto ticketsDto = JSONObject.parseObject(dto.getTicketsTask()
                .getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
        String targetPosName = Optional.ofNullable(ticketsDto.getModalData().get("targetPosName"))
                .orElse(ticketsDto.getModalData().get("targetPosCode")).toString();

        String changeTarget = targetPosName.contains("5241") ? "40NX" : "40SX";
        String agvLeaveUri = "http://192.10.13.20:9999/lzms/agvLeave?status=1&sbbh=5503&sbbh_wz=40SX";
        agvLeaveUri = agvLeaveUri.replace("5503", robot.getRobotName())
                .replace("40SX", changeTarget);
        String target = targetPosName.split(",")[0];
        String sbztResult = COMMANDS.get(targetPosName, target);
        String getSBStatus = "http://192.10.13.20:9999/sb/getSBZT?sbbh="+ target;
        log.info("需要检验换料状态:{}---连接 {}", sbztResult, getSBStatus);
        boolean warning = true;
        for (int i = 0; i < 3; i++) {
            String result = restTemplate.postForObject(agvLeaveUri, "", String.class);
            log.info("AGV换料完成离开 {}---{}", agvLeaveUri, result);
            String change = restTemplate.getForObject(
                    getSBStatus, String.class);
            JSONObject jsonObject = JSONObject.parseObject(change);
            if (jsonObject.containsKey("data") && sbztResult.equals(jsonObject.getString("data"))) {
                log.info("换料信号接收完成:");
                warning = false;
                break;
            }
            TimeUnit.SECONDS.sleep(5);
        }
        if (warning) {
            log.info("换料超时相关设备没收到信号,增加报警");
        }

    }
}
